//
//  LTNetworkTools.swift
//  微博08
//
//  Created by 123 on 16/3/2.
//  Copyright © 2016年 Tsr. All rights reserved.
//

import UIKit
import AFNetworking

class LTNetworkTools: NSObject {
    
    let afnManager: AFHTTPSessionManager
    
    // 单例
    static let sharedInstance: LTNetworkTools = LTNetworkTools()
    
    // private表示私有方法,除这个文件外的其它类是不知道这个方法的
    private override init() {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        afnManager = AFHTTPSessionManager(baseURL: baseURL)
        
        afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        super.init()
    }
    
    // MARK: Oauth授权相关
    let client_id = "1144660943"
    let client_secret = "0839a076ff4a8ba51fd934f8af5ab801"
    let redirect_uri = "http://www.baidu.com/"
    let oauthUrl = "https://api.weibo.com/oauth2/authorize"
    
    // 获得oauth授权的登录界面
    func oauthLoginUrl() -> NSURL {
        let urlString = oauthUrl + "?" + "client_id=" + client_id + "&" + "redirect_uri=" + redirect_uri
        
        return NSURL(string: urlString)!
    }
    
    // 获取access_token
    func loadAccessToken(code: String, accessTokenFinished: (response: [String: AnyObject]?, error: NSError?) -> ()) {
        // 3.3请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 3.4请求参数
        let parameter = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        // 3.5发送POST请求
        afnManager.POST(urlString, parameters: parameter, progress: nil, success: { (_, response) -> Void in
            
            // 网络工具类只赋值加载数据,不负责处理数据
            // response as? [String: AnyObject]: 表示response有可能转成[String: AnyObject],也有可能转不成返回nil
            // response as! [String: AnyObject]: 表示response一定能转成[String: AnyObject],如果转不成功,程序崩溃
            let dict = response as? [String: AnyObject]
            // 获得数据,调用闭包
            accessTokenFinished(response: dict, error: nil)
            }) { (_, error) -> Void in
                accessTokenFinished(response: nil, error: error)
        }
        
    }
    
    // 发送GET请求
    func loadUserInfo(finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        
        // 3.判断access_token
        // 守卫 access_token 可以在后面的代码直接使用,不要放到代码块里面,减少嵌套
        guard let access_token = LTUserAccountViewModel.sharedInstance.userAccount?.access_token else {
            print("没有 access_token")
            return
        }
        
        // 4.判断uid
        guard let uid = LTUserAccountViewModel.sharedInstance.userAccount?.uid else {
            print("没有 uid")
            return
        }
        
        // 5.url
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 6.准备参数
        let paramaters = ["access_token": access_token, "uid": uid]
        
        // 7.发送请求
        afnManager.GET(urlString, parameters: paramaters, progress: nil, success: { (_, result) -> Void in
            // 8.调用闭包
            finished(result: result as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }

}
